package com.easpeed.comon.ui

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.Log;
import com.bigyu.utils.Logger
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.TextView
import androidx.core.util.Consumer
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableBoolean
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.Marker
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.map.bmsdk.ui.BaseUI
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.common.CommonConsts
import com.easpeed.comon.DataConsts
import com.easpeed.comon.bean.BaseData
import com.easpeed.comon.bean.LatLngCommon
import com.easpeed.comon.bean.toLatLng
import com.easpeed.comon.consts.ConstsOpticalData
import com.easpeed.comon.dialog.RouteUploadDialog
import com.easpeed.comon.memorycache.CommonMemoryCache
import com.easpeed.comon.utils.ApiHelper.createLine
import com.easpeed.comon.utils.ApiHelper.createOptical
import com.easpeed.comon.utils.CacheHelper
import com.easpeed.comon.utils.CommonOperateUtils
import com.easpeed.comon.utils.Line
import com.easpeed.comon.utils.LocationHelper
import com.easpeed.comon.utils.NetHelper
import com.easpeed.comon.utils.Optical
import com.easpeed.comon.utils.Record
import com.easpeed.comon.utils.YFMapUtilsBaidu
import com.easpeed.comon.utils.isUser
import com.easpeed.elevator.BuildConfig
import com.easpeed.elevator.R
import com.easpeed.elevator.bean.LineBean
import com.easpeed.elevator.bean.OpticalBean
import com.easpeed.elevator.bean.RouteBean
import com.easpeed.elevator.databinding.ActivityCommonRouteBinding
import com.easpeed.elevator.ui.LineManageActivity
import com.easpeed.elevator.utils.CallbackInterface
import com.easpeed.elevator.utils.NoticeDialog
import com.easpeed.elevator.utils.WwAdapter
import com.easpeed.elevator.utils.WwViewHolder
import com.easpeed.user.UserBaseActivity
import com.easpeed.user.UserDeviceInfoActivity
import com.easpeed.user.UserLineManageActivity
import com.easpeed.user.dialog.UserDialogHelper
import com.easpeed.user.utils.FileHelper
import com.gyf.immersionbar.ImmersionBar
import org.opencv.imgproc.Imgproc.drawMarker
import java.text.DecimalFormat
import kotlin.random.Random


class CommonRouteActivity : UserBaseActivity() {
    var isManageModel = ObservableBoolean(false)

    var binding: ActivityCommonRouteBinding? = null
    private var cacheRouteList: ArrayList<RouteBean> = arrayListOf()

    lateinit var locationHelper: LocationHelper
    private var baiduMap: BaiduMap? = null

    private var baiduMapHelper: YFMapUtilsBaidu? = null

    private var locationmarker: Marker? = null

    override fun initView() {
        locationHelper = LocationHelper()
        locationHelper.init(this)
        baiduMapHelper = YFMapUtilsBaidu(mContext)
        cacheRouteList.clear()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_common_route)
        binding?.data = this
        initLineView(binding?.recylerviewLine)
        loadData()


        ImmersionBar.with(this)
            .statusBarDarkFont(false) // 设置状态栏字体为深色
            .transparentStatusBar()  // 透明状态栏
//            .fitsSystemWindows(false)
            .titleBarMarginTop(binding?.titleBar)
            .init()

        locationHelper.setResultCallback { location ->
            //mapView 销毁后不在处理新接收的位置
            if (location == null || binding?.mapView == null) {
                return@setResultCallback
            }
//            val locData = MyLocationData.Builder()
//                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
//                .direction(location.direction).latitude(location.latitude)
//                .longitude(location.longitude).build()
//            baiduMap?.setMyLocationData(locData)

            baiduMapHelper?.apply {
                if (locationmarker != null && locationmarker?.isRemoved != true) {

                } else {
                    locationmarker = baiduMapHelper?.drawMarker(LatLng(location.latitude, location.longitude), getMapIcon(R.mipmap.ic_my_location), true )
                }
                locationmarker?.position = LatLng(location.latitude, location.longitude)
                locationmarker?.rotate = location.radius
            }

            if (isFirstLocate) {
                isFirstLocate = false
                baiduMapHelper?.moveCameraZoomTo(LatLng(location.latitude, location.longitude), 18f, 100)
            }
        }


        binding?.titleBar?.setOnClickListener {
            mActivity.finish()
        }


        binding?.mapView?.apply {
            baiduMap = this.map
            baiduMapHelper?.setMap(this.map)
            baiduMap?.isMyLocationEnabled = true
            locationHelper.start(mActivity, false)

            baiduMap?.setOnMarkerClickListener {
                Logger.e("", "===========>initView: marker click")
                val bean = it.extraInfo?.getParcelable<RouteBean>("route")
                    ?: return@setOnMarkerClickListener false
                Logger.e("TAG", "initView: ${bean}")

                RouteUploadDialog().show(mContext, bean, true) { routeBean, type ->
                    Logger.e("TAG", "initView: ${bean}")
//                    cacheRouteList.remove(bean)
                    if (type == 1) {
//                        cacheRouteList.add(bean)
                        ToastUtils.showShort("修改成功")
                    } else {
                        ToastUtils.showShort("删除成功")
                    }
                    netForRecordList("${bean.opticalId}")

//                    FileHelper.saveRouteData(mContext, cacheRouteList)
                }
                return@setOnMarkerClickListener true
            }
        }
        initListener()
    }

    private fun initListener() {
        binding?.setting?.setOnClickListener {
            CommonOperateUtils.moveTo(mContext, OfflineMapActivity::class.java)

        }
        // 管理/取消管理
        binding?.manage?.setOnClickListener {
            isManageModel.set(true)

            wwAdapterLine?.notifyDataSetChanged()
        }
        binding?.manageExit?.setOnClickListener {
            isManageModel.set(false)
            wwAdapterLine?.notifyDataSetChanged()
        }

        binding?.createLine?.setOnClickListener {
            //创建线路
            createLine("", "新增线路", CallbackInterface { message: String? ->
                readCreateLine(message)
            })
        }
    }


    /**
     * 路由点 故障点
     */
    private fun getPointView(bean: RouteBean): View {
        val view = LayoutInflater.from(mContext).inflate(R.layout.marker_route_point, null, false)



        if (bean.routeTypeId == "1") {
            view.findViewById<View>(R.id.name).setBackgroundResource(R.drawable.shape_map_route_ly)
            view.findViewById<View>(R.id.line).setBackgroundColor(resources.getColor(R.color.green))
        } else {
            view.findViewById<View>(R.id.line).setBackgroundColor(resources.getColor(R.color.red))
            view.findViewById<View>(R.id.name).setBackgroundResource(R.drawable.shape_map_route_gz)
        }
        if (bean.distance.isNullOrEmpty()) {
            view.findViewById<TextView>(R.id.name).text = "${DataConsts.getRouteType(bean.routeTypeId)}"
        } else {
            try {
                val decimalFormat = DecimalFormat("#.###") // # 表示可选位
                val formattedDistance: String = decimalFormat.format(bean.distance?.toFloat())
                view.findViewById<TextView>(R.id.name).text = "${DataConsts.getRouteType(bean.routeTypeId)}@${formattedDistance}km"
            } catch (e: Exception) {
                e.printStackTrace()
                view.findViewById<TextView>(R.id.name).text = "${DataConsts.getRouteType(bean.routeTypeId)}@${bean.distance}km"
            }
        }
        return view
    }


    private fun loadData() {
        netForLineList()
//        val routeList = FileHelper.readRouteData(mContext)
//        val lineData = FileHelper.readLineData(mContext)
//        cacheRouteList.clear()
//        cacheRouteList.addAll(routeList)
//
//        lineList.clear()
//        lineList.addAll(lineData)
//        wwAdapterLine?.notifyDataSetChanged()
//
//        if (BuildConfig.DEBUG) {
//            ToastUtils.showShort("当前测试环境，随机偏移点坐标")
//            cacheRouteList.forEach {
//                it.lat = it.lat?.let {
//                    "${it.toDouble() + Random.nextInt(0, 9) / 10000.0}"
//                }
//                it.lng = it.lng?.let {
//                    "${it.toDouble() + Random.nextInt(0, 9) / 10000.0}"
//                }
//            }
//        }
//        if (BuildConfig.DEBUG && cacheRouteList.isEmpty()) {
//            cacheRouteList.add(RouteBean().apply {
//                lat = "31.848845"
//                lng = "117.241529"
//                lineName = "1号线"
//                routeTypeId = "1"
//            })
//            cacheRouteList.add(RouteBean().apply {
//                lat = "31.847845"
//                lng = "117.242529"
//                lineName = "2号线"
//                routeTypeId = "2"
//
//            })
//            cacheRouteList.add(RouteBean().apply {
//                lat = "31.844845"
//                lng = "117.243529"
//                lineName = "3号线"
//                routeTypeId = "1"
//
//            })
//            cacheRouteList.add(RouteBean().apply {
//                lat = "31.846945"
//                lng = "117.244529"
//                lineName = "4号线"
//                routeTypeId = "2"
//            })
//        }
    }

    private var isFirstLocate = true


    private var isRefreshData = false
    override fun onResume() {
        super.onResume()
        if (isRefreshData) {
            isRefreshData = false
            loadData()
        }

        binding?.mapView?.onResume()
        locationHelper.start(this, false)
    }

    override fun onPause() {
        super.onPause()
        binding?.mapView?.onPause()
    }

    override fun onDestroy() {
        binding?.mapView?.onDestroy()
        locationHelper.release()
        locationHelper.stop()
        super.onDestroy()
    }

    val showRouteList = ArrayList<RouteBean>()

    private fun renderRouteData(lineId: String?, opticalId: String?) {
        val lineBean = lineList.find { it.lineId == lineId }
        val opticalBean = lineBean?.opticalList?.find { it.id == opticalId }
        renderRouteData(lineBean, opticalBean)
    }

    private fun renderRouteData(lineData: LineBean?, opticalData: OpticalBean?) {
        if (lineData == null || opticalData == null) {
            return
        }
        showRouteList.clear()
//        cacheRouteList.forEach {
//            if (it.lineId == lineData.lineId && it.opticalId == opticalData.id) {
//                it.lineName = lineData.lineName
//                it.opticalName = opticalData.name
//                showRouteList.add(it)
//            }
//        }


        netForRecordList(opticalData.id)


    }

    private fun renderRouteData() {
        baiduMap?.clear()

        val lineList = showRouteList.mapNotNull { LatLngCommon(it.lat, it.lng).toLatLng() }
        showRouteList.forEach { bean ->
            val start = LatLngCommon(bean.lat, bean.lng).toLatLng()
            baiduMapHelper?.apply {
                isFirstLocate = false
                pointBastInScreen(lineList)
                drawTextureLine(lineList, getMapIcon("icon_map_line.png"))

                val marker = drawMarker(start, getMapIcon(getPointView(bean)), true)
                marker?.zIndex = Integer.MAX_VALUE
//                marker?.isClickable = true
                marker?.extraInfo = Bundle().apply {
                    putParcelable("route", bean)
                }
            }
        }
    }

    private var currentOpticalId: String? = null

    val lineList = ArrayList<LineBean>()
    private var wwAdapterLine: WwAdapter<LineBean>? = null
    private fun initLineView(recyclerView: RecyclerView?) {
        wwAdapterLine = object : WwAdapter<LineBean>() {
            override fun initRecyclerView(mContext: Context, adapter: WwAdapter<LineBean>) {
                val manager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                recyclerView?.layoutManager = manager
                recyclerView?.adapter = adapter
                isUseEmpty(true)
            }

            override fun getEmptyLayoutId(): Int {
                return R.layout.user_empty_item_route
            }

            override fun getLayoutId(): Int {
                return R.layout.user_route_item_line_info
            }

            override fun emptyView(holder: WwViewHolder?) {
                super.emptyView(holder)
                holder?.itemView?.setOnClickListener {
                    isRefreshData = true
                    if (isUser()) {
                        CommonOperateUtils.moveTo(mContext, UserLineManageActivity::class.java)
                    } else {
                        LineManageActivity.start(mContext)
                    }
                }
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun convert(holder: WwViewHolder, bean: LineBean, position: Int) {
                holder.setText(R.id.tv_line_name, bean.lineName)
                holder.setVisible(R.id.recyclerView_optical, bean.isExpand)

                val isManage = isManageModel.get()

                holder.setVisible(R.id.delete, isManage)
                holder.setVisible(R.id.edit, isManage)
                holder.setActivated(R.id.detail, bean.isExpand)


                val recyclerViewOptical = holder.getView<RecyclerView>(R.id.recyclerView_optical)

                initLineView(recyclerViewOptical, bean, bean.opticalList as ArrayList<OpticalBean>)


                holder.setOnClickListener(R.id.layout_line_info, View.OnClickListener { v: View? ->
                    if (bean.opticalList.isNullOrEmpty()) {
                        ToastUtils.showShort("该线路暂未发现光缆，请先前往路线管理添加光缆信息")
                    }
                    bean.isExpand = !bean.isExpand
                    expandLine[bean.lineId.toString()] = bean.isExpand
                    wwAdapterLine?.notifyDataSetChanged()
                })


                holder.setOnClickListener(R.id.delete) {
                    val str = "确定删除 ${bean.lineName} 吗？\n" +
                            "该线路含有${bean.opticalList.size}个相关光缆，将会一起删除。"
                    UserDialogHelper.showNoticeDialog(mContext, "删除线路", str, sureClick = {
                        netForDeleteLine(bean.lineId)
                    })
                }

                holder.setOnClickListener(R.id.edit, View.OnClickListener { v: View? ->
                    createLine(bean.lineName, "编辑线路", CallbackInterface { message: String? ->
                        if (checkLineName(message, true)) {
                            netForUpdateLine(bean.lineId, "$message")
                        }
                    })
                })

                holder.setOnClickListener(R.id.add, View.OnClickListener { v: View? ->
                    createOptical(bean.opticalList, "新增光缆", null, CallbackInterface { opticalBean: OpticalBean ->
                        val map = HashMap<String, Any?>()
                        map["remark"] = opticalBean.remark
                        map["opticalName"] = opticalBean.name
                        map["fibreLength"] = opticalBean.length
                        map["fibreCodes"] = opticalBean.codeMark
                        map["fibreNum"] = opticalBean.number.toInt()
                        map["hop"] = opticalBean.zjd
                        map["opticalLevel"] = opticalBean.level.toInt()
                        map["lineId"] = bean.lineId
                        map["deviceCode"] = CommonConsts.targetDeviceId
                        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
                        netForCreateOptical(map)
                    })
                })
            }
        }.create(mContext, lineList)
    }


    private fun initLineView(recyclerView: RecyclerView, mData: LineBean, opticalList: ArrayList<OpticalBean>): WwAdapter<OpticalBean?>? {
        return object : WwAdapter<OpticalBean>() {
            override fun initRecyclerView(mContext: Context, adapter: WwAdapter<OpticalBean>) {
                val manager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                recyclerView.layoutManager = manager
                recyclerView.adapter = adapter
            }

            override fun getLayoutId(): Int {
                return R.layout.user_route_item_optical_info
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun convert(holder: WwViewHolder, bean: OpticalBean, position: Int) {
                bean.parentId = mData.lineId
                bean.parentName = mData.lineName
                holder.setText(R.id.tv_line_name, bean.name)


                val isManage = isManageModel.get()

                holder.setVisible(R.id.delete, isManage)
                holder.setVisible(R.id.edit, isManage)
                holder.setActivated(R.id.base, bean.id == currentOpticalId)

                holder.setOnClickListener(R.id.root) {
//                    bean.isExpand = !bean.isExpand
                    currentOpticalId = bean.id
                    renderRouteData(mData, bean)
                    notifyDataSetChanged()
                    wwAdapterLine?.notifyDataSetChanged()
                }
                holder.setOnClickListener(R.id.add) {
                    val routeBean = RouteBean().apply {
                        this.strength = ""
                        this.lat = "${CommonMemoryCache.devicelat}"
                        this.lng = "${CommonMemoryCache.devicelon}"

                        this.lineId = mData.lineId
                        this.lineName = mData.lineName
                        this.opticalId = bean.id
                        this.opticalName = bean.name
                    }
                    RouteUploadDialog().show(mContext, routeBean, false) { routeBean, type ->
                        ToastUtils.showShort("上传成功")
                        netForRecordList(bean.id)
                    }
                }

                holder.setOnClickListener(R.id.delete, View.OnClickListener { view: View? ->
                    val str = "确定删除 ${bean.name} 吗？删除后不可撤回。"
                    UserDialogHelper.showNoticeDialog(mContext, "删除光缆", str, sureClick = {
                        netForDeleteOptical(bean.id)
                    })
                })
                holder.setOnClickListener(R.id.edit, View.OnClickListener { view: View? ->
                    createOptical(opticalList, "编辑光缆", bean, CallbackInterface { opticalBean: OpticalBean ->
                        val map = HashMap<String, Any>()
                        map["id"] = opticalBean.id
                        map["remark"] = opticalBean.remark
                        map["opticalName"] = opticalBean.name
                        map["fibreLength"] = opticalBean.length
                        map["fibreCodes"] = opticalBean.codeMark
                        map["fibreNum"] = opticalBean.number.toInt()
                        map["hop"] = opticalBean.zjd
                        map["opticalLevel"] = opticalBean.level.toInt()
                        map["lineId"] = opticalBean.parentId
                        map["deviceCode"] = CommonConsts.targetDeviceId
                        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
                        netForUpdateOptical(map)
                    })
                })
            }
        }.create(mContext, opticalList)
    }

    private val expandLine = HashMap<String, Boolean>()
    private val expandOptical = HashMap<String, Boolean>()
    private lateinit var netHelper: NetHelper


    private fun netForLineList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForLineList(isLoading = true, map, Consumer<BaseData<List<Line>>> {
            if (it.code == 200) {
                lineList.clear()
                it.data?.map {
                    LineBean().apply {
                        this.lineName = it.lineName
                        this.lineId = it.id.toString()
                        this.isExpand = expandLine[it.id.toString()] ?: false
                    }
                }?.let { it1 -> lineList.addAll(it1) }
                wwAdapterLine?.notifyDataSetChanged()
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForRecordList(id: String) {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        if (BuildConfig.DEBUG) {
            ToastUtils.showShort("测试环境随机偏移坐标")
        }
        netHelper.netForRecordList(isLoading = true, id, map, Consumer<BaseData<List<Record>>> {
            if (it.code == 200) {
                showRouteList.clear()
                it.data?.forEach { data ->
                    showRouteList.add(RouteBean().apply {
                        this.lineId = data.lineId.toString()
                        this.opticalId = data.opticalId.toString()
                        this.lat = data.latitude.toString()
                        this.lng = data.longitude.toString()
                        this.routeTypeId = data.recordType.toString()
                        this.codeMark = data.fibreCodes
                        this.distance = data.distance.toString()
                        this.addressRemark = data.placeDesc
                        this.routeRemark = data.remark
                        this.routeId = data.id.toString()


                        this.lineName = lineList.find { it.lineId == data.lineId.toString() }?.lineName
                        this.opticalName = lineList.find { it.lineId == data.lineId.toString() }?.opticalList?.find { it.id == data.opticalId.toString() }?.name
                        this.routeType = DataConsts.getRouteType(data.recordType.toString())


                        data.pictures?.split(";")?.map { it.trim() }?.filter { it.isNotEmpty() && it.isNotBlank() }?.let {
                            this.imagePath = ArrayList<String>().apply {
                                addAll(it)
                            }
                        }


                        //测试环境随机偏移坐标
//                        if (BuildConfig.DEBUG) {
//                            this.lat = this.lat?.let {
//                                "${it.toDouble() + Random.nextInt(0, 9) / 10000.0}"
//                            }
//                            this.lng = this.lng?.let {
//                                "${it.toDouble() + Random.nextInt(0, 9) / 10000.0}"
//                            }
//                        }
                    })
                }
                renderRouteData()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForOpticalList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        lineList.forEach {
            it.opticalList?.clear()
        }
        netHelper.netForListOptical(isLoading = true, map, Consumer<BaseData<List<Optical>>> {
            if (it.code == 200) {
                if (it.data != null) {
                    it.data?.forEach { data ->

                        lineList.find { it.lineId == data.lineId.toString() }?.let {
                            if (it.opticalList == null) {
                                it.opticalList = arrayListOf()
                            }
                            it.opticalList?.add(OpticalBean(data.id.toString()).apply {
                                this.remark = data.remark
                                this.length = data.fibreLength
                                this.codeMark = data.fibreCodes
                                this.number = data.fibreNum.toString()
                                this.zjd = data.hop
                                this.level = data.opticalLevel.toString()
                                this.name = data.opticalName
                                this.parentId = data.lineId.toString()
                                this.isExpand = expandOptical[data.id.toString()] ?: false
                            })
                        }
                    }
                }
                wwAdapterLine?.notifyDataSetChanged()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }


    /**
     * 创建线路弹框
     */
    private fun createLine(defaultTxt: String, title: String, callbackInterface: CallbackInterface<String>) {
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(R.layout.user_dialog_create_line).setClickBtnDismissDialog(true).setCanCancel(true).setCanceledOnTouchOutside(true).create()
        dialog.setOnclickListener(R.id.close, View.OnClickListener { v: View? ->
            dialog.dismiss()
        })
        dialog.setText(R.id.input, defaultTxt)
        dialog.setText(R.id.title, title)
        dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
            val input = (dialog.getView(R.id.input) as TextView).text.toString()
            callbackInterface.onCallback(input)
        })
//        dialog.setWidth(ScreenUtils.getScreenWidth())
        dialog?.setDialogWith((ScreenUtils.getScreenWidth() * 0.5f).toInt())

        dialog.setGravity(Gravity.BOTTOM or Gravity.CENTER_VERTICAL)
        dialog.show()
    }

    private fun checkLineName(lineName: String?, isEdit: Boolean): Boolean {
        if (TextUtils.isEmpty(lineName)) {
            if (isEdit) {
                ToastUtils.showShort("编辑线路失败 ,请输入线路名称")
            } else {
                ToastUtils.showShort("创建线路失败 ,请输入线路名称")
            }
            return false
        }
        return true
    }

    private fun readCreateLine(lineName: String?) {
        if (TextUtils.isEmpty(lineName)) {
            ToastUtils.showShort("创建线路失败 ,请输入线路名称")
        } else {
            netForCreate(lineName)
        }
    }

    /**
     * 创建光缆
     */
    private fun createOptical(opticalList: MutableList<OpticalBean>, defaultTxt: String, bean: OpticalBean?, callbackInterface: CallbackInterface<OpticalBean>) {
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(R.layout.user_dialog_create_optical).setClickBtnDismissDialog(false).setCanCancel(true).setCanceledOnTouchOutside(true).create()
//        dialog.setDialogWith(ScreenUtils.getScreenWidth(), 0)
//        dialog.setGravity(Gravity.BOTTOM)
        dialog?.setDialogWith((ScreenUtils.getScreenWidth() * 0.5f).toInt())

        dialog.setGravity(Gravity.BOTTOM or Gravity.CENTER_VERTICAL)
        dialog.setOnclickListener(R.id.close, View.OnClickListener { v: View? ->
            dialog.dismiss()
        })
        if (bean != null) {
            dialog.setText(R.id.name, bean.name)

            try {
                val level = ConstsOpticalData.options.getOrNull(bean.level.toInt())
                dialog.setText(R.id.level, level)
            } catch (e: Exception) {
                e.printStackTrace()
                dialog.setText(R.id.level, "")
            }
            dialog.setText(R.id.zjd, bean.zjd)
            dialog.setText(R.id.count, bean.number)
            dialog.setText(R.id.number, bean.codeMark)
            dialog.setText(R.id.length, bean.length)
            dialog.setText(R.id.remark, bean.remark)
        }
        dialog.setText(R.id.title, defaultTxt)

        val autoCompleteTextView = dialog.getView(R.id.level) as AutoCompleteTextView
        // 准备下拉选项数据
        val adapter: ArrayAdapter<String> = ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, ConstsOpticalData.options)
        autoCompleteTextView.setAdapter(adapter)
        autoCompleteTextView.setOnClickListener(View.OnClickListener { v: View? -> autoCompleteTextView.showDropDown() })


        dialog.setOnclickListener(R.id.reduce, View.OnClickListener { v: View? ->
            val count = dialog.getText(R.id.count)
            if (count != null && !count.isEmpty()) {
                val result = count.toInt() - 1
                dialog.setText(R.id.count, result.toString() + "")
            }
        })
        dialog.setOnclickListener(R.id.add, View.OnClickListener { v: View? ->
            val count = dialog.getText(R.id.count)
            if (count != null && !count.isEmpty()) {
                val result = count.toInt() + 1
                dialog.setText(R.id.count, result.toString() + "")
            }
        })

        dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
            for (opticalBean in opticalList) {
                if (bean != null && TextUtils.equals(bean.id, opticalBean.id)) {
                    continue
                }
                if (TextUtils.equals(opticalBean.name, dialog.getText(R.id.name))) {
                    ToastUtils.showShort("光缆不可名称重复")
                    return@OnClickListener
                }
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.name))) {
                ToastUtils.showShort("请输入光缆名称")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.level))) {
                ToastUtils.showShort("请选择光缆级别")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.zjd))) {
                ToastUtils.showShort("请输入中继段")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.count))) {
                ToastUtils.showShort("请输入纤芯数量")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(dialog.getText(R.id.number))) {
                ToastUtils.showShort("请输入纤芯编号")
                return@OnClickListener
            }
            if (dialog.getText(R.id.number).split("；".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size > dialog.getText(R.id.count).toInt()) {
                ToastUtils.showShort("纤芯数量应大于等于纤芯编号数量")
                return@OnClickListener
            }

            if (TextUtils.isEmpty(dialog.getText(R.id.length))) {
                ToastUtils.showShort("请输入纤芯长度")
                return@OnClickListener
            }
            var opticalBean = OpticalBean()
            if (bean != null) {
                opticalBean = bean
            }
            opticalBean.name = dialog.getText(R.id.name)
            opticalBean.level = ConstsOpticalData.options.indexOf(dialog.getText(R.id.level)).toString()
            opticalBean.zjd = dialog.getText(R.id.zjd)
            opticalBean.number = dialog.getText(R.id.count)
            opticalBean.codeMark = dialog.getText(R.id.number)
            opticalBean.length = dialog.getText(R.id.length)
            opticalBean.remark = dialog.getText(R.id.remark)
            callbackInterface.onCallback(opticalBean)
            dialog.dismiss()
        })

        dialog.show()
    }

    private fun netForCreate(lineName: String?) {
        val map = HashMap<String, Any>()
        map["lineName"] = "$lineName"
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForCreateLine(true, map, Consumer<BaseData<Line>> {
            if (it.code == 200) {
                ToastUtils.showShort("创建线路成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForDeleteLine(lineId: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForDeleteLine(lineId, map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("删除线路成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForUpdateLine(lineId: String, name: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        map["id"] = lineId
        map["lineName"] = name
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        netHelper.netForUpdateLine(map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("修改成功")
                netForLineList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForDeleteOptical(opticalId: String) {
        val map = HashMap<String, Any>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForDeleteOptical(opticalId, map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                ToastUtils.showShort("删除光缆成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForUpdateOptical(map: HashMap<String, Any>) {
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForUpdateOptical(map, Consumer<BaseData<Optical>> {
            if (it.code == 200) {
                ToastUtils.showShort("修改成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }

    private fun netForCreateOptical(map: HashMap<String, Any?>) {
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(this)
        }
        netHelper.netForCreateOptical(true, map, Consumer<BaseData<Optical>> {
            if (it.code == 200) {
                ToastUtils.showShort("创建成功")
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        }
        )
    }
}